
using System.Reflection.Metadata.Ecma335;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Xml.Linq;
using Microsoft.AspNetCore.Mvc;
using ST.Core;
using ST.Data;
using ST.ModelVM;
using ST.ModelVM.ProtocolDefine;
using ST.ModelVM.ProtocolSim;
using ST.ModelVM.ProtocolSimHost;
using ST.ModelVM.ProtocolSimLog;
using ST.Receiver.Tasks;

namespace ST.Simulator.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    public class ProtocolSimHostController : ControllerBase
    {
        IRepository<Data.ProtocolDefine> __IRepositoryProtocolDefine;
        IRepository<Data.ProtocolSim> _IRepositoryProtocolSim;
        IRepository<Data.ProtocolSimHost> _IRepository;



        public ProtocolSimHostController(IRepository<Data.ProtocolDefine> repository1,
            IRepository<Data.ProtocolSim> repository2,
            IRepository<Data.ProtocolSimHost> repository3)
        {
            __IRepositoryProtocolDefine = repository1;
            _IRepositoryProtocolSim = repository2;
            _IRepository = repository3;



        }
        [HttpPost("InitAdd")]
        public ProtocolSimHostVM InitAdd(Int64Model qm)
        {
            var msim = _IRepositoryProtocolSim.GetById(qm.Id);
            var mdefine = __IRepositoryProtocolDefine.GetById(msim.ProtocolDefineId);
            var m = _IRepository.GetById(qm.Id);
            var content = ST.Core.Util.JSON.DeserializeObject<ProtocolDefineVM>(mdefine.Content);
            var mm = new ProtocolSimHostVM();
            mm.Id = ST.Core.Util.IdUtil.NextId();
            mm.HostId = 1;
            mm.HostName = "";
            mm.ProtocolSimId = qm.Id;
            foreach (var mcs in content.ZSBCS)
            {
                mm.ZSBCS.Add(new ModelVM.ProtocolSim.ProtocolZSBCSValue
                {
                    Id = mcs.Id,
                    Name = mcs.Name,
                    Value = 0
                });
            }
            return mm;

        }
        [HttpPost("Add")]
        public ProtocolSimHostVM Add(ProtocolSimHostVM mm)
        {
            if (mm.HostId == 0)
            {
                throw new MyException("主机号必须输入");
            }
            var msim = _IRepositoryProtocolSim.GetById(mm.ProtocolSimId);

            var c = _IRepository.GetAll().Where(a => a.ProtocolSimId == msim.Id && a.HostId == mm.HostId).Count();
            if (c > 0)
            {
                throw new MyException("主机号重复");
            }


            var mhost = new ProtocolSimHost();
            mhost.Id = ST.Core.Util.IdUtil.NextId();
            mm.Id = mhost.Id;

            mhost.ProtocolSimId = mm.ProtocolSimId;
            mhost.HostId = mm.HostId;
            mhost.HostName = $"机号：{mhost.HostId}";
            mhost.Content = ST.Core.Util.JSON.SerializeObject(mm.ZSBCS);

            mhost.WaitMs = mm.WaitMs;
            mhost.WaitTimes = mm.WaitTimes; 
            mhost.ReqInterval = mm.ReqInterval;

            mhost.CrtDt = DateTime.Now;
            mhost.EdtDt = DateTime.Now;
            _IRepository.DB.Add(mhost);

            _IRepository.DB.SaveChanges();

            return mm;
        }


        [HttpPost("Edit")]
        public ProtocolSimHostVM Edit(ProtocolSimHostVM mm)
        {


            var m = _IRepository.GetById(mm.Id);
            if (mm.HostId == 0)
            {
                throw new MyException("主机号必须输入");
            }
            if (m.HostId != mm.HostId)
            {
                var c = _IRepository.GetAll().Where(a => a.ProtocolSimId == mm.ProtocolSimId && a.HostId == mm.HostId).Count();
                if (c > 0)
                {
                    throw new MyException("主机号重复");
                }
            }
            m.HostId = mm.HostId;
            m.HostName = $"机号：{m.HostId}";
            m.Content = ST.Core.Util.JSON.SerializeObject(mm.ZSBCS);
            m.EdtDt = DateTime.Now;

            m.WaitMs = mm.WaitMs;
            m.WaitTimes = mm.WaitTimes;
            m.ReqInterval = mm.ReqInterval;
            _IRepository.DB.SaveChanges();

            return mm;
        }

        [HttpPost("Delete")]
        public async Task<Data.ProtocolSimHost> Delete(Int64Model mm)
        {
            var m = _IRepository.GetById(mm.Id);
            _IRepository.DB.Remove(m);

            await _IRepository.DB.SaveChangesAsync();
            return m;
        }

        [HttpPost("Detail")]
        public ProtocolSimHostVM Detail(Int64Model qm)
        {
            var m = _IRepository.GetById(qm.Id);
            var mm = new ProtocolSimHostVM();
            mm.ZSBCS = ST.Core.Util.JSON.DeserializeObject<List<ProtocolZSBCSValue>>(m.Content);
            mm.Id = m.Id;
            mm.HostId = m.HostId;
            mm.HostName = m.HostName;
            mm.ProtocolSimId = m.ProtocolSimId;
            return mm;
        }

        [HttpPost("DataPage")]
        public PageResult<EquipmentAttributeVM> DataPage(ProtocolSimHostDataQM qm)
        {
            return TransMain.Instance.DataPage(qm);
        }

        [HttpPost("ListCmd")]
        /// <returns></returns>  0 正常    BreakToken  1  EndToken 2    timeout 3   检验失败4
        public async Task<List<UInt16Value>> ListCmd(Int64Model qm)
        {
            var m = await _IRepository.GetByIdAsync(qm.Id);
            var sim=_IRepositoryProtocolSim.GetById(m.ProtocolSimId);
            var define= __IRepositoryProtocolDefine.GetById(sim.ProtocolDefineId);
            var mm=ST.Core.Util.JSON.DeserializeObject<ModelVM.ProtocolDefine.ProtocolDefineVM>(define.Content); 
            var r=new List<UInt16Value>();            
            foreach (var v in mm.GDZL)
            {
                r.Add(new UInt16Value { Name = v.Name });
            }
            return r;
        }



        [HttpPost("Cmd")]
        /// <returns></returns>  0 正常    BreakToken  1  EndToken 2    timeout 3   检验失败4
        public async Task<ApiResult<string>> CmdAsync(ProtocolCmdVM qm)
        {
           var r= await   TransMain.Instance.CmdAsync(qm);
            var res=new ApiResult<string>();  

            switch (r)
            {
                case 0:
                   res.Message="执行成功";
                    break;
                case 1:
                case 2:
                    res.Message = "99";
                    res.Message = "中断异常";
                    break;
                case 3:
                   
                    res.Message = "99";
                    res.Message = "通讯超时";
                    break;
                case 4:
                    
                    res.Message = "99";
                    res.Message = "反馈异常";
                    break;
                default:
                  
                    res.Message = "99";
                    res.Message = "系统异常";
                    break;
            }
            return res;
        }
    }
}